package com.msi.manning.network;

import com.msi.manning.network.Rectify;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

public class Result extends Activity {
    private static final String CLASSTAG = Result.class.getSimpleName();

	public static final int MAIN_ID = Menu.FIRST;
    
    private TextView factof;
    private EditText gram;
    
    private String choice;
    private ListView nutrients;
    private Rectify resolve = new Rectify();
    ArrayList<HashMap<String, String>> facts;
    
    @Override
    public void onCreate(final Bundle icicle) {
        super.onCreate(icicle);
        Log.d(Constants.LOGTAG, "Entered Result.java");
        
        // Getting Data first.
        Bundle extras = getIntent().getExtras();
        if (extras != null)
        {
        	choice = extras.getString("choices");
        	Log.d(Constants.LOGTAG, " " + Result.CLASSTAG + " Choice = " + choice);
        }
        else
        {
            Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + "No Choice passed");
        }
        	
        final String url = "http://teamsupercool.x10hosting.com/result2.php?keyword=" + choice;
        // Stores into facts
        this.facts = getHttpResponse(url);
        
        // Start Window.
        //requestWindowFeature(Window.FEATURE_NO_TITLE);
        requestWindowFeature(Window.FEATURE_CONTEXT_MENU);
        this.setContentView(R.layout.result);
    	Log.d(Constants.LOGTAG, "Main Layout Set");

        this.factof 	= (TextView) findViewById(R.id.factof);
        this.gram		= (EditText) findViewById(R.id.amount);
        this.gram.addTextChangedListener(new TextWatcher(){

			public void afterTextChanged(Editable s) {
				// TODO Auto-generated method stub
		    	Log.d(Constants.LOGTAG, "User Inputted: " + s.toString());
		        ArrayList<HashMap<String, String>> tfacts = new ArrayList<HashMap<String, String>>();
		        HashMap<String, String> tmap = new HashMap<String, String>();
		        if (!s.toString().equals(""))
		    	{
		    		DecimalFormat df = new DecimalFormat("0.###");
		    		for (HashMap<String,String> eNut : facts) {
		    			String newValue = df.format(
		    					Double.valueOf(eNut.get("value")).doubleValue() 
		    					/ 100 * Integer.parseInt(s.toString())
		    			);
		    			tmap.put("cat", resolve.getName(eNut.get("cat")));
		    			tmap.put("value", newValue);
		    			tmap.put("unit", resolve.getUnit(eNut.get("unit")));
		    			tfacts.add(tmap);
		    			tmap = new HashMap<String, String>();
		    		}
		    		initListView(tfacts);
		    	}
			}

			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
			}

			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			}
        });
        
        this.nutrients = (ListView) findViewById(R.id.list_of_nutrients);
    	Log.d(Constants.LOGTAG, "View Binded");

    	// Set choice
        factof.setText(choice);
        initListView();
    }
    
        
    private void initListView() {
        /* Loads the items to the ListView. 
         * 
         * SimpleAdapter ( , list<Hash, /layout/nutriant.xml, mapping..)
         * 
         */
    	nutrients.setAdapter(new SimpleAdapter(this, facts, R.layout.nutrient,
    			new String[] {"cat", "value", "unit"}, 
    			new int[] {R.id.CAT_CELL, R.id.VALUE_CELL, R.id.UNIT_CELL}));
    }
    
    
    private void initListView(ArrayList<HashMap<String, String>> tfacts) {
        /* Loads the items to the ListView. 
         * 
         * SimpleAdapter ( , list<Hash, /layout/nutriant.xml, mapping..)
         * 
         */
    	nutrients.setAdapter(new SimpleAdapter(this, tfacts, R.layout.nutrient,
    			new String[] {"cat", "value", "unit"}, 
    			new int[] {R.id.CAT_CELL, R.id.VALUE_CELL, R.id.UNIT_CELL}));
    }
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(0, MAIN_ID, 0, R.string.menu_main).setIcon(R.drawable.search);
        //menu.add(0, TO_EXIT, 0, R.string.op_exit);
        return result;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
        case MAIN_ID:
            startActivity(new Intent(Result.this, NutritionMe.class));
            return true;
        	//return true;
        }      
        return super.onOptionsItemSelected(item);
    	//return false;
    }
    
    /**
     * Perform an HTTP GET with HttpUrlConnection.
     * 
     * @param location
     * @return
     */
    public ArrayList<HashMap<String, String>> getHttpResponse(String location) {
        URL url = null;
        //HashMap<String, String> items = new HashMap<String, String>();
        ArrayList<HashMap<String, String>> items = new ArrayList<HashMap<String, String>>();
        Log.d(Constants.LOGTAG, " " + Result.CLASSTAG + " location = " + location);

        try {
            url = new URL(location);
            Log.d(Constants.LOGTAG, " " + Result.CLASSTAG + " url = " + url);
        } catch (MalformedURLException e) {
            Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + " " + e.getMessage());
        }

        if (url != null) {

           // this.progressDialog = ProgressDialog.show(this, "working . . .", "performing HTTP request");
        	
        	try 
        	{
                HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
                BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()), 16384);
                
                String x;
                HashMap<String, String> nutrient = new HashMap<String, String>();
                while (!(x = in.readLine()).startsWith("EOF"))
                {
                	String[] tresult = x.split("::");
                	Log.d(Constants.LOGTAG, x + " " + tresult[0] + " : " + tresult[1]);
                	if(!tresult[1].equals("0.000"))
                	{
                		nutrient.put("cat", resolve.getName(tresult[0]));
                		nutrient.put("value", tresult[1]);
                		nutrient.put("unit", resolve.getUnit(tresult[0]));
                		items.add(nutrient);
                		nutrient = new HashMap<String, String>();
                	}
                }
                
                in.close();
                urlConn.disconnect();

            } catch (IOException e) {
                Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + " " + e.getMessage());
            }

            //this.progressDialog.dismiss();
        } else {
            Log.e(Constants.LOGTAG, " " + Result.CLASSTAG + " url NULL");
        }
        return items;
    }
    
}
